<?php

$server = new swoole_websocket_server("0.0.0.0", 9501);

$server->on('open', function (swoole_websocket_server $server, $request) {
    $arr = ['total'=>0,'id'=>[]];
    //当前用户连接信息
    foreach ($server->connections as $key => $value) {
        $arr['total'] += 1;
        $arr['id'][] = $value;
    }
    $arr = var_export($arr ,true);
    file_put_contents( __DIR__ .'/log.txt' , $arr);
});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    global $client;
    $data = $frame->data;

    foreach($server->connections as $fd) {
      echo PHP_EOL . '  connection id is  ' . $fd . 'content is ' . $data;
      $server->push($fd, $data );
    }

});

$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n \$ser is ";
    foreach($ser->connections as $id) {
      $msg = [
        'time' => '123123',
        'msg' => "{$fd} is quited",
        'username' => 'admin'
      ];
      $msg = json_encode($msg);
      $ser->push($id, $msg );
    }
});

$server->start();
